package jmine.tec.extensions.forms;

import java.util.List;

import jmine.tec.extensions.ExtensionsApiMessages;
import jmine.tec.utils.collection.Mapper;
import jmine.tec.utils.collection.MapperUtils;
import bancosys.tec.exception.BusinessException;
import bancosys.tec.exception.CompoundMessageHolder;
import bancosys.tec.exception.LocalizedMessageHolder;

/**
 * @author wagner.tsuchiya
 */
public final class FormHandlerHelper {
    /**
     * Private constructor.
     */
    private FormHandlerHelper() {

    }

    /**
     * Validates the given form, throwing an exception if invalid
     * 
     * @param <F> form type.
     * @param form form
     * @param formHandler the form handler.
     */
    public static <F> void validateThrowException(F form, FormHandler<F> formHandler) {
        List<String> validationErrors = formHandler.validate(form);
        if (!validationErrors.isEmpty()) {
            throw new BusinessException(new CompoundMessageHolder("\n").addMessages(MapperUtils.mapList(validationErrors,
                    new Mapper<String, LocalizedMessageHolder>() {
                        public LocalizedMessageHolder apply(String input) {
                            return ExtensionsApiMessages.REMOTE_ERROR.create(input);
                        }
                    })));
        }
    }
}
